<?php
/*
* Description: Users class
*/
class StatusMessages extends DbBase{

	var $id;
	var $user_id;
	var $status_message;
	var $status;
	var $created_on;
	
    // constructor
	public function __construct() {
        $this->table_name = 'status_messages';
    }
	
	public function get_latest_active_status(){
		$sql  = "SELECT * ";
		$sql .= " FROM ".$this->table_name;
		$sql .= " WHERE user_id=$this->user_id AND status=true";
		$sql .= " ORDER BY created_on DESC";
		$sql .= " LIMIT 1";
		
		$result = array_shift($this->query($sql));
		$this->construct_attributes($result);
	}
	
	public function clear_status(){
		$this->get_latest_active_status();
		$this->status = false;
		$this->update();
	}
	
	public function find_inactive_messages(){
		$result = array();
		
		$sql  = "SELECT * ";
		$sql .= " FROM ".$this->table_name;
		$sql .= " WHERE user_id=$this->user_id AND status=false";
		$sql .= " ORDER BY created_on DESC";
		
		$rows = $this->query($sql);
		foreach($rows as $index => $row){
			$status = new StatusMessages();
			$status->set_attributes($row);
			$result[$index] = $status;
		}
		return $result;
	}
	
	public function insert(){
		$sql  = "INSERT INTO $this->table_name";
		$sql .= "(user_id, status_message, status)";
		$sql .= " VALUES($this->user_id, '$this->status_message', true)";
		
		//insert if successful set others to status false;
		if($this->execute($sql)){
			$sql  = "UPDATE $this->table_name";
			$sql .= " SET status=false";
			$sql .= " WHERE id!=".$this->get_last_id();
			$sql .= " AND user_id=$this->user_id";
			$this->execute($sql);
			return true;
		}
		return false;
	}
	
	public function update(){
		$sql  = "UPDATE $this->table_name";
		$sql .= " SET user_id=$this->user_id,";
		$sql .= " status_message='$this->status_message',";
		$sql .= " status=".(int)$this->status;
		$sql .= " WHERE id=$this->id";
		
		//update
		return $this->execute($sql);
	}
	
	// CLASS METHODS
	public static function get_active_status($user_id){
		$status = new StatusMessages();
		
		$status->user_id = $user_id;
		$status->get_latest_active_status();
		return $status;
	}
	
	public static function get_all_old_status($user_id){
		$status = new StatusMessages();
		$status->user_id = $user_id;
		return $status->find_inactive_messages();
	}
	
	// PRIVATE METHODS
	private function get_last_id(){
		$sql  = "SELECT max(id) as max_id ";
		$sql .= " FROM $this->table_name";
		$sql .= " WHERE user_id=$this->user_id";
		
		$result = array_shift($this->query($sql));
		return $result['max_id'];
	}
	
	public function delete(){ throw new Exception("method unimplemented yet"); }
	public function select(){ throw new Exception("method unimplemented yet"); }
}
?>